class Documents::BaseController < ApplicationController
  before_filter :authenticate_user!,      :except => [:index, :show]
  before_filter :check_moderators_access, :only   => [:new, :create, :edit, :update, :destroy]
  before_filter :get_current_document,    :except => [:index, :new, :create]
  before_filter :parse_tags,              :only   => [:create, :update]
  before_filter :get_tags,                :only   => :index

  helper_method :document_type

  protected
    def document_type
      case controller_name
        when 'news'         then :news
        when 'publications' then :publication
        when 'articles'     then :article
        when 'conferences'  then :conference
      end
    end

    def get_current_document
      case document_type
        when :news        then @news = News.find(params[:id])
        when :publication then @publication = Publication.find(params[:id])
        when :article     then @article = Article.find(params[:id])
        when :conference  then @conference = Conference.find(params[:id])
      end
    end

    def parse_tags
      labels = (params[:tags] || []).reject { |c| c.empty? }
      redirect_to root_path, :alert => "Error" and return if labels.count > 5   # TODO Move to settings
      tags = []
      labels = labels.inject([]) { |result, h| result << h unless result.map{|i| i.downcase}.include?(h.downcase); result }
      labels.each do |label|
        tag = Tag.find_or_initialize_by_label(label)
        tags << tag if tag.valid?
      end
      params[document_type][:document_attributes].update(:tags => tags)
    end

    def get_tags
      @tags = Tag.all
      @doc_type_tags = Tag.by_document_type document_type
    end
end
